<?php

namespace app\admin\controller\profession;

use app\admin\model\profession\Profession;
use app\common\controller\Backend;
use app\common\exception\BusinessException;
use app\common\model\ProfessionCourse;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 题库列表(题库属于公共数据,某个专业可以自己来提取自己的题库)
 *
 * @icon fa fa-circle-o
 */
class Course extends Backend
{

    /**
     * Course模型对象
     * @var \app\admin\model\profession\Course
     */
    protected $model = null;

    /**
     * Profession模型对象
     * @var Profession
     */
    protected $professionModel = null;


    /**
     * Course模型对象
     * @var \app\admin\model\Course
     */
    protected $courseModel = null;

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\profession\Course();
        $this->courseModel = new \app\admin\model\Course();
        $this->professionModel = new Profession;
    }

    /**
     * 查看
     */
    public function index($ids = null)
    {
        // 查询专业
        $profession = $this->professionModel->find($ids);

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->alias('pc')
                ->with(['exam', 'region', 'courseInfo'])
                ->where($where)
                ->where('profession_id', '=', $ids)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->view->assign('ids', $ids);
        $this->view->assign('profession', $profession);
        return $this->view->fetch();
    }

    /**
     * add
     * @return string
     * @throws Exception
     */
    public function add()
    {
        // 请求参数
        $param = $this->request->param();

        // 提取参数
        $profession_id = $param['profession_id'] ?? 0;

        if ($this->request->isAjax()) {
            // 提取参数
            $course_id = $param['course_id'] ?? 0;
            if (!$course_id) {
                $this->error('请求参数不得为空');
            }

            // 查询专业信息
            $profession_info = $this->professionModel->find($profession_id);
            if (!$profession_info) {
                $this->error('专业信息不存在');
            }

            // 查询题库信息
            $course_info = $this->courseModel->find($course_id);
            if (!$course_info) {
                $this->error('题库信息不存在');
            }

            // 查询专业题库是否已经绑定
            $where = [
                'profession_id' => $profession_id,
                'course_id' => $course_id
            ];
            $count = $this->model->where($where)->count();
            if ($count) {
                $this->error('此题库已经绑定过当前专业');
            }

            // 绑定题库到当前专业
            $data = [
                'profession_id' => $profession_id,
                'course_id' => $course_id,
            ];
            $isAdd = $this->model->save($data);
            if (!$isAdd) {
                $this->error('绑定题库失败');
            }
            $this->success();
        }
        $this->view->assign('profession_id', $profession_id);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        
        // 查询题库信息
        $course_info = $this->courseModel->find($row['course_id']);
        if (!$course_info) {
            $this->error('题库信息不存在');
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->view->assign('course_info', $course_info);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        
        // 处理exam_time字段
        $params['exam_time'] = !empty($params['exam_time']) ? strtotime($params['exam_time']) : 0;
        
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 批量设置考试时间
     */
    public function batchsetexamtime()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $ids = $params['ids'];
            $exam_time = isset($params['exam_time']) ? strtotime($params['exam_time']) : 0;
            
            if (empty($ids)) {
                $this->error(__('Parameter %s can not be empty', 'ids'));
            }
            
            if (empty($exam_time)) {
                $this->error(__('考试时间不能为空'));
            }
            
            $count = 0;
            Db::startTrans();
            try {
                $list = $this->model->where('id', 'in', $ids)->select();
                foreach ($list as $index => $item) {
                    $count += $item->allowField(true)->isUpdate(true)->save(['exam_time' => $exam_time]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        
        $ids = $this->request->get('ids');
        $this->view->assign('ids', $ids);
        return $this->view->fetch();
    }
}
